package whu.edu.service;

import com.sun.istack.NotNull;
import whu.edu.Dao.ProductRepository;
import whu.edu.Entity.Product;
import whu.edu.Entity.Supplier;
import whu.edu.Exception.ProductException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.*;

/**
 * @author 86159
 */
@org.springframework.stereotype.Service
public class ProductService {
    @Autowired
    private ProductRepository ProductJPARepository;

    /**
     * 添加商品
     */
    public Product addProduct(Product  p) throws ProductException{
        if(p.getId() != null){
            if(ProductJPARepository.findById(p.getId()).isPresent()){
                throw new ProductException("商品已存在");
            }
        }
        return ProductJPARepository.save(p);
    }
    /**
     * 利用id查询商品
     */
    public Product getProduct(int id){

        return ProductJPARepository.findById(id).get();
    }
    /**
     * 返回所有商品
     */
    public List<Product> getAll(){
        return  ProductJPARepository.findAll();
    }
    /**
     * 返回供货商id相同的商品
     */
    public List<Product > getProductbys(int id){//供货商的商品。
        List<Product > temp = ProductJPARepository.findAll();
        List<Product > result = new ArrayList<>();
        for(Product  c : temp){
            List<Supplier> suppliers = c.getSuppliers();
            for(Supplier s : suppliers){
                if(s.getId() == id){result.add(c);}
            }
        }
        return result;
    }
    /**
     * 分页查询
     */
    public Page<Product> findProducts(@NotNull Map<String, Object>condition, @NotNull Pageable pageable){
        return ProductJPARepository.findAll((root, q, cb)-> {
            List<Predicate> pList =new ArrayList<>();//用于组合所有的查询条件。
            if(condition.containsKey("name")){
                pList.add(cb.like(root.get("name"),"%"+condition.get("name")+"%"));
            }
            if(condition.containsKey("price")){
                pList.add(cb.le(root.get("price"),(float)condition.get("price")));
            }
            return cb.and(pList.toArray(new Predicate[pList.size()]));
        },pageable);
    }

    public void updateProduct(int id, Product c) throws ProductException{
        if(c.getId()!=null){
            if(!ProductJPARepository.findById(id).isPresent()){
                throw new ProductException("商品不存在");
            }
            ProductJPARepository.saveAndFlush(c);
        }
    }

    public void deleteProduct(int id){
        ProductJPARepository.deleteById(id);
    }
}